package com.jing.cloud.service.user.dao.impl;

import com.jing.cloud.service.dao.impl.DbDaoImpl;
import com.jing.cloud.service.user.bean.Password;
import com.jing.cloud.service.user.constant.UserConstant;
import com.jing.cloud.service.user.dao.PwDao;
import org.springframework.stereotype.Repository;


@Repository
public class PwDaoImpl extends DbDaoImpl<Password> implements PwDao {

    @Override
    public void invaildPwHandler(Password pw) {
        Password pw4update = new Password();
        pw4update.setId(pw.getId());
        int wrongNumber = pw.getWrongNumber();
        wrongNumber++;
        pw.setWrongNumber(wrongNumber);
        pw4update.setWrongNumber(wrongNumber);
        if (wrongNumber >= UserConstant.PW_WRONG_TIME_LOCK) {
            long frozenBefore = System.currentTimeMillis() + UserConstant.PW_LOCK_MS;
            pw.setFrozenBefore(frozenBefore);
            pw4update.setFrozenBefore(frozenBefore);
        }
        pw4update.forUpdate();
        update(pw4update);
    }

    @Override
    public void vaildPwHandler(Password pw) {
        int wn = pw.getWrongNumber();
        long fb = pw.getFrozenBefore();
        if (wn > 0 || fb > System.currentTimeMillis()) {
            Password pw4update = new Password();
            pw4update.setId(pw.getId());
            pw4update.setWrongNumber(0);
            pw.setWrongNumber(0);
            pw4update.setFrozenBefore(0L);
            pw.setFrozenBefore(0L);
            pw4update.forUpdate();
            update(pw4update);
        }
    }
}
